//
//  RootViewController.m
//  JReaderSDK
//
//  Created by linziyuan on 2017/7/17.
//  Copyright © 2017年 creative. All rights reserved.
//

#import "RootViewController.h"
#import "ConstDefine.h"

@interface RootViewController ()

@end

@implementation RootViewController

static RootViewController * singleRootViewController = nil;

- (instancetype)init
{
    if (self = [super init]) {
        singleRootViewController = self;
    }
    return self;
}

+ (instancetype)shareLastInstance
{
    return singleRootViewController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

//解压html文件到书本目录下
+ (void)unArchiveHtmlFileToFlowBookWithBookInfo:(TABLE_BOOKS*)tb_book{
    //获取当前html的版本
    NSString* flowHtmlEdition = [NetDownSupportFiles getInstance].getFlowBookHtmlEdition;
    
    NSString* zipFilePath = [[DataProcessing shareSingle].indexHtmlDirector stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",flowHtmlEdition]];
    NSString* unArchiveFilePath = [DataProcessing bookPathForBookID:tb_book.bookId];
    NSString* jsonFilePath = [unArchiveFilePath stringByAppendingPathComponent:@"version.json"];
    NSData *jsonData = [[NSData alloc]initWithContentsOfFile:jsonFilePath];
    NSDictionary* jsonDict = nil;
    if (jsonData) {
        jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    }
    NSString* flowHtmlEdition_inBook = jsonDict[@"vno"];
    if (!flowHtmlEdition_inBook || ![flowHtmlEdition_inBook isEqualToString:flowHtmlEdition]) {
        [DataProcessing unZipFromZipFilePath:zipFilePath ToUnZipPath:unArchiveFilePath];
    }
}

//外部打开阅读器
+ (void)outEnterToReadBookWithTbBook:(TABLE_BOOKS*)tb_book currentVC:(UIViewController *)currentVC success:(void(^)())success failure:(void(^) ())failure{

    //处理在阅读器内打开图书
    //[self managerOpenBookActionInReadVCWithTb_Book:tb_book];
    
    //如果是流式阅读器,将html包解压到书本目录下
    if ([tb_book.readSource isEqualToString:@"flow"]) {
        [self unArchiveHtmlFileToFlowBookWithBookInfo:tb_book];
    }
    if ([UIAlertView isAlertShow]) {
        if (failure) {
            failure();
        }
        return;
    }
    if (!tb_book) {
        if (failure) {
            failure();
        }
        return;
    }
    //
    NSDictionary* dict = [DataProcessing getBookJsonInfo:tb_book.bookId];
    NSDictionary* evaluateDict = [DataProcessing getEvaluatingJsonInfo:tb_book.bookId];
    
    BookScreenType bScreenType = BookScreenType_vertical;
    if ([dict objectForKey:@"screen"] && notNULL([dict objectForKey:@"screen"])) {
        bScreenType = [[dict objectForKey:@"screen"] integerValue];
    }
    UIViewController* topVC = ((UINavigationController*)[UIApplication sharedApplication].delegate.window.rootViewController).visibleViewController;
    if (![topVC isKindOfClass:[ReadBookVOrH_VC class]]) {
        //
        [[DBHelper shareInstance] selectQuiz_Books:@(tb_book.bookId).description complete:^(NSDictionary *reDict_quiz) {
            [[DBHelper shareInstance] selectTalk_Books:@(tb_book.bookId).description complete:^(NSDictionary *retDict_talk) {
                //
                //[self stopAudioPlay:NO];
                NSArray* list_talk = retDict_talk[@"talk"];
                TABLE_TALK_LIST* tb_talk = [list_talk firstObject];
                
                UIViewController* topVC = ((UINavigationController*)[UIApplication sharedApplication].delegate.window.rootViewController).visibleViewController;
                if (![topVC isKindOfClass:[ReadBookVOrH_VC class]]) {
                    //
                    if ([tb_book.readSource isEqualToString:@"quiz"]) {
                        //suportfile 存在
                        NSString *htmlPath = [DataProcessing getQuizPublicHtmlPath];
                        BOOL suprtExist = [[NSFileManager defaultManager] fileExistsAtPath:htmlPath];
                        //当前资源存在
                        BOOL currentExist = [[NSFileManager defaultManager] fileExistsAtPath:[DataProcessing quizDataPathForBookOriginalID:tb_book.originalId]];
                        if (suprtExist && currentExist) {
                            NSString *urlStr = [NSString stringWithFormat:@"%@?quizidx=%@",htmlPath,@(tb_book.originalId).description];;
                            WebViewController *webVC = [[WebViewController alloc] init];
                            webVC.url = urlStr;
                            webVC.showType = SettingShowType_Quiz;
                            webVC.popUpType = WebPopUpType_Present;
                            webVC.closeType = @"quiz";
                            webVC.isfullScrean = YES;
                            [currentVC presentViewController:webVC animated:YES completion:nil];
                            if (success) {
                                success();
                            }
                        }else {
                            if (failure) {
                                failure();
                            }
                            if (!suprtExist) {
                                NSLog(@"quiz公共文件不存在");
                            }
                            if (!currentExist) {
                                NSLog(@"当前book资源不存在");
                            }
                        }
                    }else if([tb_book.readSource isEqualToString:@"flow"]){
                        //流式排版
                        if (failure) {
                            failure();
                        }
                    }else{
                        //
                        if (dict) {
                            //
                            UserInfo* uinfo = [[CacheData shareSingle] getUserLoginInfo];
                            ReadBookVOrH_VC* bvc = [[ReadBookVOrH_VC alloc] init];
                            //
                            bvc.tb_book = tb_book;
                            bvc.bookid = tb_book.bookId;
                            bvc.bookOid = tb_book.originalId;
                            bvc.pageNums = tb_book.pageNums;
                            bvc.readSource = tb_book.readSource;
                            bvc.showInfoDict = tb_book.showInfo;
                            //bvc.operMap = tb_book.operMap;
                            //bvc.isCatched = [tb_book.operMap[@"hwInfo"][@"catched"] boolValue];
                            //bvc.linkQuizBookId = tb_book.linkQuizBookId;
                            bvc.coverImageUrl = [DataProcessing fullBookCoverImageUrl:tb_book.thumb];
                            if (tb_book.infoDefine) {
                                bvc.coverImg = ((UIImage*)tb_book.infoDefine);
                            }
                            if (evaluateDict) {
                                bvc.evaluateDict = evaluateDict;
                            }
                            bvc.hurdleNo = [DataProcessing shareSingle].hurdleNo;
                            bvc.activityId = [DataProcessing shareSingle].activityId;
                            bvc.bookName = [DataProcessing chooseLanguageFromCN:tb_book.name_zh andEN:tb_book.name_en];
                            bvc.bookDict = dict;
                            //bvc.quizUrl = book.quizUrl;
                            bvc.currentIndex = [[CacheData shareSingle] getLastOpenPageForBook:tb_book.bookId forUid:uinfo.uid];
                            bvc.isAutoRead = NO;
                            bvc.needPageMap = YES;
                            bvc.rotation_back = [UIApplication sharedApplication].statusBarOrientation;
                            if (bScreenType == BookScreenType_vertical) {
                                bvc.rotation_to =  UIInterfaceOrientationPortrait;
                            }else{
                                bvc.rotation_to =  UIInterfaceOrientationLandscapeRight;
                            }
                            NSArray* list_quiz = reDict_quiz[@"quiz"];
                            TABLE_QUIZ* tb_quiz = [list_quiz firstObject];
                            bvc.quizUrl = tb_quiz.quizUri;
                            bvc.quizEdition = tb_quiz.edition;
                            bvc.talkInfo = tb_talk;
                            BOOL isFavor = [[Merge_MineAndFavor_Manager defaultManager] isFavorWithBookId:tb_book.bookId];
                            if (isFavor) {
                                bvc.isFavorited = YES;
                            }
                            //
                            if ([bvc isRotationHorizontal:bvc.rotation_to]) {
                                [bvc setMyRotationToHorizontal];
                            }else{
                                [bvc setMyRotationToVertical];
                            }
                            [DataProcessing do_Async_quick:^{
                                [[DB_NetFollowReading shareSingle] reUpdateRecordAndASRResultWithBookId:tb_book.bookId];
                            }];
                            [DataProcessing do_Main_quick:^{
                                if (success) {
                                    success();
                                }
                                [currentVC presentViewController:bvc animated:[DataProcessing shareSingle].canWindowRotation completion:nil];
                            }];
                        }else{
                            if (failure) {
                                failure();
                            }
                            //[self setBookDownFail:tb_book.bookId];
                            [[NetDownloadBooks shareSingle] cancelDownBooks:tb_book.bookId];
                            [DataProcessing deleteBookFiles:tb_book.bookId];
                            UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
                            [[CacheData shareSingle] deleteBookCache:tb_book.bookId forUid:uinfo.uid];
                            NSLog(@"无法打开书本~book.json");
                        }
                    }
                }
            }];
        }];
    }
}


- (void)load_UserInfo_Server_Login:(Process)processSuccess {}
- (void)stopAudioPlay:(BOOL)cleanData {}
- (void)cleanLimitedDateAndReflashLibrary {}
- (void)checkTo_Home {}
- (void)yzt_Login:(BOOL)isNeedRelogin {}
- (void)yzt_Login:(BOOL)isNeedRelogin complete:(void(^)(BOOL isSuccess))complete{};
- (void)initialJRAdudioData{};
+ (void)mergeBookSubWithBaseBookTable:(TABLE_BOOKS*)bookModal BookSub:(NSDictionary*)bookSub{};
- (void)refreshBookHouseIsMine:(BOOL)isMine{};
- (void)openSingelBookWithBookId:(NSInteger)bookId tbBook:(TABLE_BOOKS*)tb_book isClick:(BOOL)isClick{};
- (void)refreshAboutMeStoryCard{};
- (void)reflashHomePage{};
- (void)load_UinfoAuthority:(BOOL)isloadBaseNeeded{};
- (void)changeToToolBarType:(NSString *)type{};

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
